//
//  ImageLoaderDatabossVersion.m
//  JUImageGalleryDemo
//
//  Created by Ju on 15/8/21.
//  Copyright (c) 2015年 juwenz. All rights reserved.
//

#import "ImageLoaderDatabossVersion.h"
#import "DataBoss.h"

@interface ImageLoaderDatabossVersion ()

@property (nonatomic, strong) ASINetworkQueue *queue;
@property (nonatomic, strong) NSMutableDictionary *requestDictionary;

@end

@implementation ImageLoaderDatabossVersion

#pragma mark - 公开
- (void)requsetImageWithImageURI:(NSString *)imageURI successCallback:(void (^)(id request,UIImage *image))successHandler failureCallback:(void (^)(id request,NSString *error))failureHandler {
    [self.requestImageURIs addObject:imageURI];
    id request = [DataBoss requsetAndCacheImage:imageURI queue:self.queue completion:^(ASIHTTPRequest *request, UIImage *image, NSString *errorMsg) {
        [self cancelRequestWithImageURI:imageURI];
        if (errorMsg) {
            failureHandler(request,errorMsg);
        }else {
            successHandler(request,image);
        }
    }];
    if (request) {
        [self.requestDictionary setObject:request forKey:imageURI];
    }
    

}

- (void)cancelAllRequest {
    for (ASIHTTPRequest *request in [self.queue operations]) {
        [request clearDelegatesAndCancel];
    }
    [self.queue cancelAllOperations];
}

- (NSString *)currentImageUrl {
    return @"";
}

- (NSString *)cachePath {
    return @"";
}

- (void)cancelRequestWithImageURI:(NSString *)imageURI {
    ASIHTTPRequest *request = [self.requestDictionary objectForKey:imageURI];
    if (request) {
        [request clearDelegatesAndCancel];
    }
    [self.requestDictionary removeObjectForKey:imageURI];
}

#pragma mark - 私有

#pragma mark - 属性
- (NSMutableSet *)requestImageURIs {
    if (!_requestImageURIs) {
        _requestImageURIs = [[NSMutableSet alloc] initWithCapacity:8];
    }
    return _requestImageURIs;
}

- (ASINetworkQueue *)queue {
    if (!_queue) {
        _queue = [[ASINetworkQueue alloc] init];
    }
    return _queue;
}

- (NSMutableDictionary *)requestDictionary {
    if (!_requestDictionary) {
        _requestDictionary = [NSMutableDictionary dictionary];
    }
    return _requestDictionary;
}

@end
